<style lang="scss" scoped>
.el-scrollbar {
  display: flex;
  flex-direction: row;

  width: 100%;
}
</style>

<template>
  <el-dialog
    title="修改父级"
    :visible.sync="showDialog"
    :close-on-click-modal="false"
    @close="$emit('update:visible', false)"
  >
    <p>待修改项</p>
    <el-table
      :data="children"
      style="width: 100%"
      height="200"
      border
    >
      <el-table-column
        prop="id"
        label="编号"
        width="80"
      />

      <el-table-column
        prop="name"
        label="名称"
      />
    </el-table>

    <p>选择父级</p>
    <div>
      <el-cascader
        v-model="parent_id"
        style="width:100%"
        :options="concatList"
        :props="{ emitPath: false, checkStrictly: true, label: 'name', value: 'id' }"
        clearable
        filterable
      />
    </div>

    <p>密码</p>
    <div>
      <el-input v-model="password" type="password" style="width: 180px;" />
    </div>

    <div slot="footer">
      <el-button @click="showDialog = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import _ from 'lodash'

import { updateParent } from '@/api/tariff'

export default {

  name: 'UpdateParent',

  props: {
    visible: {
      type: Boolean,
      default: true
    },

    children: {
      type: Array,
      default: () => []
    },

    list: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      showDialog: this.visible,

      parent_id: '',
      password: '812345'
    }
  },

  computed: {
    concatList() {
      return [].concat([
        {
          name: '顶级',
          id: '0'
        }
      ], this.list)
    }
  },

  watch: {
    visible() {
      this.showDialog = this.visible
    }
  },

  methods: {
    submit() {
      if (this.parent_id === '') {
        this.$message.error('请选择父级')
        return
      }

      if (this.password === '') {
        this.$message.error('请输入密码')
        return
      }

      const index = _.findIndex(this.children, {
        id: this.parent_id
      })
      // 如果父级选择为待修改项中的 则提示不能修改
      if (~index) {
        this.$message.error('父级不是待修改项中的值')
        return
      }

      updateParent({
        parent_id: this.parent_id,
        child_id: this.children.map(item => item.id),
        password: this.password
      })
        .then(res => {
          this.parent_id = ''
          // this.password = ''

          this.$message.success('修改成功')
          this.$emit('reloadList')
          this.showDialog = false
        })
    }
  }
}
</script>
